'use strict';
const UniID = require('uni-id-common');

exports.main = async (event, context) => {
  // 解析请求体
  let body = event;
  if (event.body !== undefined) {
    try {
      body = JSON.parse(event.body);
    } catch (e) {
      return {
        code: 400,
        message: "请求体解析失败",
        error: e.message
      };
    }
  }

  if (!body.supervisorToken) {
    return {
      code: 400,
      message: "缺少必要参数supervisorToken"
    };
  }

  const uniID = UniID.createInstance({ context });

  // 通过token获取用户信息
  const verifyRes = await uniID.checkToken(body.supervisorToken);
  if (verifyRes.code !== 0) {
    return {
      code: 401,
      message: "无效的token或已过期"
    };
  }

  const supervisorId = verifyRes.uid;

  try {
    const db = uniCloud.database();
    const _ = db.command;

    const page = body.page || 1;
    const pageSize = body.pageSize || 10;
    const skip = (page - 1) * pageSize;

    // 查询当前督导负责的咨询师
    const relationRes = await db.collection('sc_relations')
      .where({
        supervisor_id: supervisorId
      })
      .field({ consultant_id: true })
      .get();

    const assignedIds = relationRes.data.map(item => item.consultant_id);

    // 获取所有已被分配的咨询师ID（不区分哪个督导）
    const allAssignedRes = await db.collection('sc_relations')
      .field({ consultant_id: true })
      .get();
    const allAssignedIds = allAssignedRes.data.map(item => item.consultant_id);

    // assignedList: 不分页，返回所有该督导负责的咨询师
    let assignedList = [];
    let assignedTotal = 0;

	if (assignedIds.length > 0) {
	  const assignedRes = await db.collection('consultants')
		.where({
		  user_id: _.in(assignedIds),
		})
		.field({
		  _id: true,
		  user_id: true,
		  name: true,
		  create_date: true
		})
		.orderBy('create_date', 'desc')
		.get();

	  assignedList = await Promise.all(assignedRes.data.map(async item => {
		const tokenRes = await uniID.createToken({ uid: item.user_id });
		return {
		  ...item,
		  user_id: tokenRes.token
		};
	  }));
	  assignedTotal = assignedList.length;
	}

    // unassignedList: 添加分页逻辑
    const userRes = await db.collection('uni-id-users')
      .where({
        is_consultant: 1,
        _id: _.nin(allAssignedIds)
      })
      .field({ _id: true })
      .get();

    const unassignedUserIds = userRes.data.map(item => item._id);
    let unassignedList = [];
    let unassignedTotal = unassignedUserIds.length;

    if (unassignedUserIds.length > 0) {
      const pagedIds = unassignedUserIds.slice(skip, skip + pageSize); // 手动分页
    
      const unassignedRes = await db.collection('consultants')
        .where({
          user_id: _.in(pagedIds),
        })
        .field({
          _id: true,
          user_id: true,
          name: true,
          create_date: true
        })
        .orderBy('create_date', 'desc')
        .get();
    
      unassignedList = await Promise.all(unassignedRes.data.map(async item => {
        const tokenRes = await uniID.createToken({ uid: item.user_id });
        return {
          ...item,
          user_id: tokenRes.token
        };
      }));
    }
    return {
      code: 200,
      message: "获取咨询师列表成功",
      data: {
        assignedList,
        assignedTotal,
        page,
        pageSize,
        totalPages: Math.ceil(unassignedTotal / pageSize),
        unassignedList
      }
    };
  } catch (error) {
    console.error('获取咨询师列表失败:', error);
    return {
      code: 500,
      message: "服务器内部错误",
      error: error.message
    };
  }
};
